﻿using Common.Result;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Exceptions
{
    /// <summary>
    /// 通用异常过滤器
    /// 实现全局捕获异常
    /// </summary>
    public class CommonExceptionFilter : IExceptionFilter, IOrderedFilter
    {
        public int Order => int.MinValue; // 设置优先级。代替ABP vNext默认的统一异常返回

        public void OnException(ExceptionContext context)
        {
            // 1、拦截异常，进行统一包装
            if (context.Exception is CommonException commonException)
            {
                CommonResult commonResult = new CommonResult();
                commonResult.ErrorNo = commonException.ErrorNo;
                commonResult.ErrorInfo = commonException.ErrorInfo;

                // 2、返回通用异常结果
                context.Result = new JsonResult(commonResult);
            }
            else
            {
                CommonException comException = new CommonException();
                comException.ErrorNo = "-1"; // -1:通用的异常编号
                comException.ErrorInfo = context.Exception.Message;

                CommonResult commonResult = new CommonResult();
                commonResult.ErrorNo = comException.ErrorNo;
                commonResult.ErrorInfo = comException.ErrorInfo;

                // 2、返回通用异常结果
                context.Result = new JsonResult(commonResult);
            }

            // 3、异常异常，不用再处理。(停止下面执行)
            context.ExceptionHandled = true;
        }
    }
}
